'use strict';
 
import React from 'react';
import {Dialog,Field,Form,DatePicker,Input,Select,Checkbox,Pagination,Search} from 'qnui';
import Tab from 'qnui/lib/tab';
import Notice from 'qnui/lib/notice';
import Button from 'qnui/lib/button';
import Icon from 'qnui/lib/icon';
import Tag from 'qnui/lib/tag';
import { Row, Col } from 'qnui/lib/grid';
import {ajax} from 'utils/index';
import './index.scss'; 
const FormItem = Form.Item;

class Index extends React.Component {
	constructor(props) {
        super(props);
        this.field = new Field(this, {
				scrollToFirstError:true,
				onChange: (name, value) => {
						this.setState({overlayVisible:false});
				}
			});
        this.state = {
        		addResourceDialog:false,
        		removeResourceDialog:false,
        		payDialog:false,
        		orderDialog:false,
        		quantityDialog:false,
        		confirmDialog:false,
        		showConfirmed:false,
        		buyDialog:false,
        		order:{},
        		resources:[],
        		resource:{
        			name:"",
        			type:"",
        			description:"",
        			start_time:"",
        			end_time:""
        		},
        		orders:[]
        }
	}
	componentDidMount(){
		this.getVipResource();
	}
	getVipResource(){
			ajax({
			  api: 'getVipResource',
			  method: 'GET',
			  data:{}
			},(json) => {	
				this.setState({resources:json.data});
			},(json)=>{
				Dialog.alert({content: '获取列表失败！'});
			});
	}
	handleEditResource(resource){
		this.field.setValues(resource);
		this.setState({addResourceDialog:true});
		this.getVipResource();
	}
	handleAddResource(){
		this.setState({addResourceDialog:true,resource:{
			name:"",
			type:"",
			description:"",
			start_time:"",
			end_time:""
		}});
	}
	onResourceClose(){
		this.setState({addResourceDialog:false});
	}
	
	onResourceOk(){
		this.field.validate((errors, values) => {
         if (errors) {
                return false;
            }
         let p = this.field.getValues();
         	 p.start_time = p.start_time.getFullYear()+"-"+(p.start_time.getMonth()>=1&&p.start_time.getMonth()<=9?0:"")+(p.start_time.getMonth()+1)+"-"+(p.start_time.getDate()<=9?"0":"")+p.start_time.getDate()+" "+(p.start_time.getHours()<=9?"0":"")+p.start_time.getHours()+":"+(p.start_time.getMinutes()<=9?"0":"")+p.start_time.getMinutes()+":"+(p.start_time.getSeconds()<=9?"0":"")+p.start_time.getSeconds();
        		 p.end_time = p.end_time.getFullYear()+"-"+(p.end_time.getMonth()>=1&&p.end_time.getMonth()<=9?0:"")+(p.end_time.getMonth()+1)+"-"+(p.end_time.getDate()<=9?"0":"")+p.end_time.getDate()+" "+(p.end_time.getHours()<=9?"0":"")+p.end_time.getHours()+":"+(p.end_time.getMinutes()<=9?"0":"")+p.end_time.getMinutes()+":"+(p.end_time.getSeconds()<=9?"0":"")+p.end_time.getSeconds();
        					
         ajax({
			  api: 'addVipResource',
			  method: 'POST',
			  data:p
			},(json) => {	
				this.setState({addResourceDialog:false});
		      this.getVipResource();
			},(json)=>{
				if(p.id){
					Dialog.alert({content: '修改失败！'});
				}else{
					Dialog.alert({content: '添加失败！'});
				   this.getVipResource();
				}
			});
		});
	}
	handleRemoveResource(resource){
		this.setState({removeResourceDialog:true,resource});
	}
	onRemoveResourceOk(){
			ajax({
			  api: 'removeVipResource',
			  method: 'POST',
			  data:{id:this.state.resource.id}
			},(json) => {	
				this.setState({removeResourceDialog:false})
			},(json)=>{
				Dialog.alert({content: '删除失败！'});
			});
			this.getVipResource();
	}
	onRemoveResourceClose(){
		this.setState({removeResourceDialog:false});
	}
	checkEndDate(rule,date,callback){
		if(!date){
			callback('必须有一个结束时间');
		}
		if (date && Date.parse(date) < Date.parse(this.field.getValue('start_time'))) {
            callback('结束时间必须晚于开始时间！');
        } 
		if (date && Date.parse(date) < Date.parse(new Date())) {
            callback('结束时间必须晚于当前系统时间！');
        } 
		{
            callback();
        }
	}

	onPayDialogClose(){
		this.setState({payDialog:false,pay_url:""});
	}
	handlePayDialog(resource){
		let quantity = 1;
		if(resource.type=="api"){
			this.setState({quantityDialog:true,resource});
		}else{
			this.getPayUrl({
						item_code:resource.item_code,
			  	  		id:resource.id,
				      cyc_unit:1,
				      cyc_num:1,
				  	   quantity:1,
				  	  });
		}
	}
	onQuantityClose(){
		this.setState({quantityDialog:false});
	}
	onQuantityConfirm(){
		const quantity = this.field.getValue("quantity");
		this.getPayUrl({
			item_code:this.state.resource.item_code,
  	  		id:this.state.resource.id,
	      cyc_unit:1,
	      cyc_num:1,
	  	   quantity:quantity,
	  	  });
	}
	getPayUrl(params){
		ajax({
			  api: 'getPayUrl',
			  method: 'POST',
			  data:params
			},(json) => {	
				this.setState({payDialog:true,quantityDialog:false,pay_url:json.url})
			},(json)=>{
				Dialog.alert({content: '获取支付链接失败！'+json.sub_msg});
			});
	}
	handleShowOrders(){
		this.setState({showConfirmed:false});
		this.getVipOrders({page:1,page_size:10});
	}
	onSearchOrder(search){
		this.getVipOrders({page:1,page_size:10,sid:search.key,show_confirmed:this.state.showConfirmed});
	}
	showConfirmedOrders(){
		this.setState({showConfirmed:true});
		this.getVipOrders({page:1,page_size:10,show_confirmed:true});
	}
	handlOnOrderPageChange(page){
		this.getVipOrders({page,page_size:10,show_confirmed:this.state.showConfirmed});
	}
	getVipOrders(params){
		ajax({
			  api: 'getVipOrders',
			  method: 'GET',
			  data:params
			},(json) => {	
				this.setState({orderDialog:true,orders:json.orders,total:parseInt(json.total)})
			},(json)=>{
				Dialog.alert({content: '获取订单列表失败！'});
			});
	}
	onOrderDialogClose(){
		this.setState({orderDialog:false});
	}
	handleOrderConfirm(order){
		this.setState({confirmDialog:true,order});
	}
	onConfirmDialogClose(){
		this.setState({confirmDialog:false});
	}
	onConfirmDialogOk(){
		const params = {
				  fee:this.state.order.fee,
				  nick:this.state.order.nick,
				  order_id:this.field.getValue("order_id"),
				  out_order_id:this.state.order.id,
				  out_confirm_id:this.state.order.id
			  };
		ajax({
			  api: 'confirmOrder',
			  method: 'GET',
			  data:params
			},(json) => {	
					ajax({
						  api: 'confirmOrderApply',
						  method: 'GET',
						  data:{order_id:params.order_id,
							  	  id:params.out_order_id,
							     confirm_id:json.apply_result
						  }
						},(json_a) => {	
							Dialog.alert({content:"确认成功！确认单号："+ json.apply_result + json_a.msg});
						},(json_a)=>{
							Dialog.alert({content: '保存确认结果失败！'+json_a.msg});
						});
			},(json)=>{
				Dialog.alert({content: json.msg+json.sub_msg});
			});
	}
	handleApiCharge(){
		this.getPayUrl({
			item_code:"FW_GOODS-1000470791-v5",
  	  		id:0,
	      cyc_unit:1,
	      cyc_num:1,
	  	   quantity:1,
	  	   fee:3
	  	  });
	}
	handleVipInstall(){
		this.getPayUrl({
			item_code:"FW_GOODS-1000471742-1",
  	  		id:0,
	      cyc_unit:1,
	      cyc_num:1,
	  	   quantity:1,
	  	   fee:3600
	  	  });
	}
	handleEcsBuy(){
		this.getPayUrl({
			item_code:"FW_GOODS-1000470791-v3",
  	  		id:0,
	      cyc_unit:1,
	      cyc_num:1,
	  	   quantity:1,
	  	   fee:1050
	  	  });
	}
	handleRdsBuy(){
		this.getPayUrl({
			item_code:"FW_GOODS-1000470791-v2",
  	  		id:0,
	      cyc_unit:1,
	      cyc_num:1,
	  	   quantity:1,
	  	   fee:600
	  	  });
	}
	onBuyDialogClose(){
		this.setState({buyDialog:false});
	}
	onBuyOk(){
		Dialog.alert({content:"如需订购资源请旺旺留言，旺旺号：kekydream。或拨打电话15022831082"});
	};
  render() {
	  const init = this.field.init;
	  const add = (window.info.user_nick=="kekydream" || window.info.user_nick=="zlp130")?<div><Button onClick={this.handleAddResource.bind(this)}>添加资源</Button>&nbsp;<Button onClick={this.handleShowOrders.bind(this)}>查看订单</Button></div>:"";
    return <div className="home-page">
		     <Dialog visible={this.state.buyDialog}
				    onOk={this.onBuyDialogClose}
				    onCancel={this.onBuyDialogClose}
				    onClose={this.onBuyDialogClose} title="资源订购">
					<div>
						<img src={this.state.pic_url} onClick={this.onBuyOk.bind(this)} />
					</div>
				</Dialog>
		    <Dialog
					visible = {this.state.addResourceDialog}
				    onOk = {this.onResourceOk.bind(this)}
				    onCancel = {this.onResourceClose.bind(this)}
				    onClose = {this.onResourceClose.bind(this)} 
					style={{width:"680px",height:"360px"}}
		    		title = "添加资源"
					>
					<Row justify="center">
						<Form direction="ver"  size="large" field={this.field}>
					   <FormItem
							label="状态设置"
							>
					   	<Row>
					   		<Col>
						   		<Row>
						   			<FormItem required label="卖家"><Input style={{width:"100px"}}  {...init('sid',{rules: [{required: true}]})} placeholder="卖家店铺ID" /></FormItem>
						   			<FormItem required label="昵称"><Input style={{width:"100px"}}  {...init('nick',{rules: [{required: true}]})}  placeholder="卖家昵称" /></FormItem>
						   		</Row>
					   		</Col>
					   		<Col>
					   			<FormItem required label="状态"><Input  style={{width:"100px"}} {...init('status',{rules: [{required: true}]})}  placeholder="资源状态" /></FormItem>
					   		</Col>
				   		</Row>
					   </FormItem>
						   <FormItem
								label="名称设置"
								>
						   		<Row>
						   				<Col>
						   					<FormItem required label="名称"><Input  {...init('name',{rules: [{required: true}]})} placeholder="资源名称" /></FormItem>
						   				</Col>
						   				<Col>
								   			<FormItem required label="类型">
									   			<Select defaultValue="rds" {...init('type',{rules: [{required: true}]})} placeholder="选择类型">
						                        <Option value="rds">数据库</Option>
						                        <Option value="ecs">服务器</Option>
						                        <Option value="api">API调用</Option>
						                        <Option value="sms">短信</Option>
						                    </Select>
								   			</FormItem>
							   			</Col>
						   		</Row>
						   </FormItem>
						   <FormItem
								label="价格设置"
								>
						   		<Row>
						   				<Col>
						   					<Row>
							   					<FormItem required label="单价"><Input style={{width:"60px"}} {...init('unit_price',{rules: [{required: true}]})} placeholder="单价" /></FormItem>
							   					<FormItem required label="数量"><Input style={{width:"60px"}} {...init('quantity',{rules: [{required: true}]})}  placeholder="数量" /></FormItem>
					   					   </Row>
						   				</Col>
						   				<Col>
								   			<FormItem  label="计量类型">
									   			<Select {...init('counting',{rules: [{required: true}]})} defaultValue="0" placeholder="选择类型">
						                        <Option value="0">周期型</Option>
						                        <Option value="1">计量型</Option>
						                    </Select>
					                    </FormItem>
				                    </Col>
						   		</Row>
						   </FormItem>
							<FormItem
								label="时间设置"
								>
									<Row>
										<FormItem required label="开始"><DatePicker size="large" {...init('start_time',{rules: [{required: true,message:"请设置开始时间"}]})} showTime/></FormItem>
										<FormItem required label="结束"><DatePicker size="large" {...init('end_time',{rules: [{validator:this.checkEndDate.bind(this)}]})} showTime/></FormItem>
			                  </Row>
						   </FormItem>
						   <FormItem
								label="详细参数"
								>
						   		<Row>
						   			<FormItem required label="详情"><Input {...init('description',{rules: [{required: true}]})}  multiple placeholder="服务器参数等详细情况" style={{width:"380px"}}/></FormItem>
						   		</Row>
						   </FormItem>
						   <FormItem
								label="付款链接"
								>
						   		<Row>
						   			<FormItem required label="付款"><Input {...init('item_code',{rules: [{required: true}]})}  placeholder="付款链接" style={{width:"380px"}}/></FormItem>
						   		</Row>
						   </FormItem>
				  		</Form>
					</Row>
			</Dialog>
			<Dialog
				visible = {this.state.removeResourceDialog}
			    onOk = {this.onRemoveResourceOk.bind(this)}
			    onCancel = {this.onRemoveResourceClose.bind(this)}
			    onClose = {this.onRemoveResourceClose.bind(this)} 
				style={{width:"650px",height:"360px"}}
	    		title = "你确定要删除以下资源吗？"
				>
				 <Row style={{padding:"10px 0"}}>
					<Col>
					<Row>名称：{this.state.resource.name}</Row>
					<Row>类型：{this.state.resource.type}</Row>
					<Row>详情：{this.state.resource.description}</Row>
					<Row>开始时间：{this.state.resource.start_time}</Row>
					<Row>结束时间：{this.state.resource.end_time}</Row>
					</Col>
				 </Row>
			</Dialog>
			<Dialog
				visible = {this.state.payDialog}
			    onOk = {this.onPayDialogClose.bind(this)}
			    onCancel = {this.onPayDialogClose.bind(this)}
			    onClose = {this.onPayDialogClose.bind(this)} 
				style={{width:"650px",height:"360px"}}
	    		title = "请选择要续费的周期"
				>
				 <div style={{padding:"10px 0",textAlign:"center"}}>
				 		<a href={this.state.pay_url} target="_blank"><Button type="primary" style={{height:"50px",width:"150px"}}>续费一年</Button></a>
				 		<br />请在支付完成后联系客服
				 </div>
			</Dialog>

			<Dialog
				visible = {this.state.quantityDialog}
			    onOk = {this.onQuantityConfirm.bind(this)}
			    onCancel = {this.onQuantityClose.bind(this)}
			    onClose = {this.onQuantityClose.bind(this)} 
				style={{width:"360px"}}
	    		title = "请输入要购买的数量"
				>
				 <div style={{padding:"10px 0",textAlign:"center"}}>
				 	<Form direction="ver"  size="large" field={this.field}>
						 <FormItem
							label="购买数量"
							>
					   		<Row>
					   			<FormItem required label="数量"><Input {...init('quantity',{rules: [{required: true}]})}  placeholder="购买数量"/></FormItem>
					   		</Row>
					     </FormItem>
			      </Form>
				 </div>
			</Dialog>

			<Dialog
				visible = {this.state.confirmDialog}
			    onOk = {this.onConfirmDialogOk.bind(this)}
			    onCancel = {this.onConfirmDialogClose.bind(this)}
			    onClose = {this.onConfirmDialogClose.bind(this)} 
	    		title = "内购确认"
				>
				 <div style={{padding:"10px 0",textAlign:"center"}}>

				 <Row style={{padding:"10px 10px 10px 0 "}}>
				 金额：{this.state.order.fee/100}，商家：{this.state.order.nick}，系统订单号：{this.state.order.id}
				 </Row>
				 	<Form direction="ver"  size="large" field={this.field}>
						 <FormItem
							label="订单ID"
							>
								 <Row>
					   			<FormItem required label="淘宝订单号"><Input {...init('order_id')}  placeholder="订单ID"/></FormItem>
					   		</Row>
					     </FormItem>
			      </Form>
				 </div>
			</Dialog>
			<Dialog
				visible = {this.state.orderDialog}
			    onOk = {this.onOrderDialogClose.bind(this)}
			    onCancel = {this.onOrderDialogClose.bind(this)}
			    onClose = {this.onOrderDialogClose.bind(this)} 
				style={{width:"100%",height:"360px"}}
	    		title = "订单列表"
				>
				<div>
					<Row>
					 <Search
				        type="normal"
				        placeholder="店铺ID"
				        	onSearch={this.onSearchOrder.bind(this)}
				        	/>&nbsp;
				      <Button onClick={this.showConfirmedOrders.bind(this)}>已确认的</Button>&nbsp;
				      <Button onClick={this.handleShowOrders.bind(this)}>全部</Button>
					</Row>
					<Row style={{margin:"10px 0"}}>
						<Col span="2">店铺ID</Col>
						<Col span="2">订购周期</Col>
						<Col span="2">计量数量</Col>
						<Col span="2">资源ID</Col>
						<Col span="2">确认单ID</Col>
						<Col span="2">金额</Col>
						<Col span="4">服务号</Col>
						<Col span="2">操作</Col>
						<Col span="3">日期</Col>
					</Row>
					{
						this.state.orders.map((map)=>{

							switch(map.cyc_unit){
								case "0" :
									map.cyc_unit = "年";
									break;
								case "1":
									map.cyc_unit = "月";
									break;
								case "2":
									map.cyc_unit = "天";
									break;
							}
							return <Row style={{borderTop:"1px dashed #E0E0E0"}}>
										<Col span="2">{map.sid}</Col>
										<Col span="2">{map.cyc_num}{map.cyc_unit}</Col>
										<Col span="2">{map.quantity}</Col>
										<Col span="2">{map.resource_id}</Col>
										<Col span="2">{map.confirm_id}</Col>
										<Col span="2">{map.fee/100}</Col>
										<Col span="4">{map.item_code}</Col>
										<Col span="2"><Button onClick={this.handleOrderConfirm.bind(this,map)}>订单确认</Button></Col>
										<Col span="3">{map.time}</Col>
									</Row>
						})
					}
					<Pagination defaultCurrent={1} onChange={this.handlOnOrderPageChange.bind(this)} total={this.state.total} />,
				</div>
			</Dialog>
			<Row>
			<Button onClick={this.handleApiCharge.bind(this)}>增值API调用充值</Button>
			&nbsp;
			<Button  onClick={this.handleVipInstall.bind(this)}>高级版安装部署服务</Button>
			&nbsp;
			<Button onClick={this.handleEcsBuy.bind(this)}>服务器资源代购</Button>
			&nbsp;
			<Button onClick={this.handleRdsBuy.bind(this)}>数据库资源代购</Button>
			&nbsp;
			{add}
			</Row>
			<Row style={{padding:"35px 0 10px 0",borderBottom:"1px solid #E3E3E3"}}>
			<Col fixedSpan="5">资源名称</Col><Col fixedSpan="5">资源类型</Col><Col fixedSpan="5">资源数量</Col><Col fixedSpan="12">资源详情</Col><Col fixedSpan="5">资源单价</Col><Col fixedSpan="10">开始时间</Col><Col fixedSpan="10">结束时间</Col><Col fixedSpan="5">状态</Col><Col fixedSpan="10">操作</Col>
			</Row>
			{this.state.resources.map((resource=>{
					return <Row style={{padding:"10px 0"}}>
								<Col fixedSpan="5">{resource.name}</Col><Col fixedSpan="5">{resource.type}</Col><Col fixedSpan="5">{resource.quantity}</Col><Col fixedSpan="12">{resource.description}</Col><Col fixedSpan="5">{resource.unit_price/100}元</Col><Col fixedSpan="10">{resource.start_time}</Col><Col fixedSpan="10">{resource.end_time}</Col><Col fixedSpan="5">{resource.status}</Col><Col fixedSpan="10"><Button onClick={this.handlePayDialog.bind(this,resource)}>续费</Button>{window.info.user_nick=="kekydream"?<i><Button onClick={this.handleEditResource.bind(this,resource)}>修改</Button><Button onClick={this.handleRemoveResource.bind(this,resource)}>删除</Button></i>:""}</Col>
							 </Row>
				})
			)}
			
    </div>;
  }
}
export default Index;
